package logic

import (
	"context"
	"fmt"
	"math"
	"my-zero-tiktok/apps/user/pb/pb"
	"my-zero-tiktok/apps/user/rpc/internal/svc"
	"my-zero-tiktok/common/constant"
	"my-zero-tiktok/common/paginate"
	"my-zero-tiktok/common/set"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type FriendListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFriendListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FriendListLogic {
	return &FriendListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// FriendList 互关好友列表
func (l *FriendListLogic) FriendList(in *pb.UserListRequest) (*pb.UserListResponse, error) {
	var userIDs []int64
	offset := paginate.GetOffset(in.Page, in.PerPage)

	//pairs, err := l.svcCtx.Redis
	followKey := fmt.Sprintf("%s:%d", constant.FollowKey, in.Id)
	pairs1, err1 := l.svcCtx.Redis.ZrevrangebyscoreWithScoresCtx(l.ctx, followKey, 0, math.MaxInt)

	fanKey := fmt.Sprintf("%s:%d", constant.FanKey, in.Id)
	pairs2, err2 := l.svcCtx.Redis.ZrevrangebyscoreWithScoresCtx(l.ctx, fanKey, 0, math.MaxInt)
	fmt.Println("redis pairs:", pairs1, pairs2)

	if err1 == nil && err2 == nil {
		followIds, fanIds := make([]int64, len(pairs1)), make([]int64, len(pairs2))
		for i, pair := range pairs1 {
			id, _ := strconv.ParseInt(pair.Key, 10, 64)
			followIds[i] = id
		}
		for i, p := range pairs2 {
			id, _ := strconv.ParseInt(p.Key, 10, 64)
			fanIds[i] = id
		}
		userIDs = set.Intersection(followIds, fanIds)
	} else {
		userIDs, _ = l.svcCtx.RelationModel.FriendListByPage(l.ctx, in.Id, offset, in.PerPage)
	}

	if len(userIDs) == 0 {
		return &pb.UserListResponse{}, nil
	}

	users, _ := l.svcCtx.UserModel.UserList(l.ctx, userIDs)
	userList := make([]*pb.User, len(users))
	for i, user := range users {
		userList[i] = &pb.User{Id: user.Id, Name: user.Name}
	}
	return &pb.UserListResponse{List: userList}, nil
}
